<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background-color: bisque;
        position: fixed;
      }
    </style>
  </head>
  <body>
    <div class="box" id="box1">box1</div>
    <script>
      const box1 = document.getElementById("box1");

      window.onkeydown = function (e) {
        const key = e.key;
        const { top, left, width, height } = box1.getBoundingClientRect();
        if (key === "ArrowUp") {
          if (top < 0) {
            box1.style.top = 0 + "px";
          } else {
            box1.style.top = top - 10 + "px";
          }
        }
        if (key === "ArrowDown") {
          if (top > window.innerHeight - height) {
            box1.style.top = window.innerHeight - height + "px";
          } else {
            box1.style.top = top + 10 + "px";
          }
        }
        if (key === "ArrowLeft") {
          if (left < 0) {
            box1.style.left = 0 + "px";
          } else {
            box1.style.left = left - 10 + "px";
          }
        }
        if (key === "ArrowRight") {
          if (left > window.innerWidth - width) {
            box1.style.left = window.innerWidth - width + "px";
          } else {
            box1.style.left = left + 10 + "px";
          }
        }
      };
    </script>
  </body>
</html>
